/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.filter;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.huawei.housekeeper.utils.TokenUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatisplus切面
 *
 * @author y00464350
 * @since 2022-02-11
 */
@Component
@Log4j2
public class MybatisPlusMetaHandlerFilter implements MetaObjectHandler {

    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 新增数据执行
     *
     * @param metaObject 插入数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Date currentDate = new Date();
            // 创建时间默认当前时间
            setFieldValByName("createdTime", currentDate, metaObject);
            setFieldValByName("updatedTime", currentDate, metaObject);
            setFieldValByName("createdBy", "admin", metaObject);
            setFieldValByName("updatedBy", "admin", metaObject);
        } catch (Exception e) {
            log.warn("insertFill is error", e);
        }
    }

    /**
     * 更新数据执行
     *
     * @param metaObject 插入数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Date currentDate = new Date();
        // 修改时间
        setFieldValByName("updatedTime", currentDate, metaObject);
        try {
            setFieldValByName("updatedBy", "admin", metaObject);
        } catch (Exception e) {
            log.warn("updateFill is error", e);
        }
    }
}